import { Menu, Tray } from 'electron';

import appManager from './app';
import { config } from './config';
import { getTrayIcon, validateIcons } from './icons';
import { log } from './logger';
import windowManager from './window';

/**
 * 托盘管理器
 */
class TrayManager {
  private tray: Tray | null = null;

  /**
   * 初始化托盘
   */
  createTray(): void {
    try {
      // 检查是否启用托盘
      if (!config.getShowTrayIcon()) {
        log.info('托盘图标显示已禁用，跳过托盘创建');
        return;
      }

      // 避免重复创建
      if (this.tray) {
        log.warn('托盘已存在，跳过创建');
        return;
      }

      // 验证图标文件
      const iconValidation = validateIcons();
      if (!iconValidation.tray) {
        log.error('托盘图标文件不存在，无法创建托盘');
        return;
      }

      // 创建托盘
      const iconPath = getTrayIcon();
      this.tray = new Tray(iconPath);
      this.tray.setToolTip('Joythink AI');

      // 设置菜单
      this.updateMenu();

      // 点击托盘图标时显示窗口
      this.tray.on('click', () => {
        windowManager.show();
      });

      log.info('托盘初始化成功');
    } catch (error) {
      log.error('托盘初始化失败:', error);
    }
  }

  /**
   * 更新托盘菜单
   */
  updateMenu(): void {
    if (!this.tray) return;

    const menuTemplate: any[] = [
      {
        label: '打开主窗口',
        click: () => {
          windowManager.show();
        }
      },
      { type: 'separator' },
      {
        label: '开机启动',
        type: 'checkbox',
        checked: config.getLaunchToTray(),
        click: (menuItem) => {
          config.setLaunchToTray(menuItem.checked);
        }
      },
      {
        label: '关闭时最小化到托盘',
        type: 'checkbox',
        checked: config.getCloseToTray(),
        click: (menuItem) => {
          config.setCloseToTray(menuItem.checked);
        }
      },
      { type: 'separator' },
      {
        label: '退出',
        click: () => {
          appManager.quit();
        }
      }
    ];

    const contextMenu = Menu.buildFromTemplate(menuTemplate);
    this.tray.setContextMenu(contextMenu);
  }

  /**
   * 销毁托盘
   */
  destroy(): void {
    if (this.tray) {
      this.tray.destroy();
      this.tray = null;
      log.info('托盘已销毁');
    }
  }

  /**
   * 重新创建托盘
   */
  recreate(): void {
    this.destroy();
    this.createTray();
  }

  /**
   * 检查托盘是否已创建
   */
  isCreated(): boolean {
    return this.tray !== null;
  }
}

// 创建单例实例
const trayManager = new TrayManager();

// 默认导出
export default trayManager;
